package com.zwcloud.zw.railway.service;

import com.zwcloud.zw.railway.service.impl.TrainServiceImpl;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTask {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTask.class);

    @Resource
    private TrainServiceImpl trainService;

    // 标志位
    private volatile boolean isTwoMonthTaskRunning = false;

    // 隔二十分钟查一下次
    @Scheduled(cron = "0 0/20 * * * ?")
    public void checkAndCallApiDaily() {
        if (isTwoMonthTaskRunning) {
            log.info("【两个月数据上传中，跳过常规任务】");
            return;
        }
        log.info("【每日常规任务】检查监装表和子表上传新增数据...");
        trainService.checkFoDataAndCallApi();
    }

    // 每隔5天凌晨2点查最近两个月
    @Scheduled(cron = "0 0 2 1/5 * ?")
    public void checkAndCallApiTwoMonth() {
        try {
            isTwoMonthTaskRunning = true;
            log.info("【两个月数据上传任务】开始，暂停常规任务！");
            trainService.checkTwoMonthDataAndCallApi();
            log.info("检查运往地新增数据...");
            trainService.checkForNewDataAndCallApi();//运往地
            log.info("【两个月数据上传任务】完成，恢复常规任务。");
        } finally {
            isTwoMonthTaskRunning = false;
        }
    }
}
